package com.scau.database.utils;

import com.scau.database.utils.annotations.Transform;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 *  把两个对象相同属性中不同命名方式的属性进行赋值的工具类
 */
public class ObjectTransformUtil {
    /**
     * 驼峰命名法字段转下滑线命名法字段
     * @param o
     * @param targetClass
     * @param <T>
     * @return
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public static <T> T camelCase2UnderScoreCase(Object o,Class<T> targetClass) throws IllegalAccessException, InstantiationException {
        T t = targetClass.newInstance();
        Class<?> oClass = o.getClass(); // 源对象
        Annotation[] declaredAnnotations = oClass.getDeclaredAnnotations();
        for(Annotation annotation : declaredAnnotations){
            // 拿到所有的注解
            System.out.println(annotation);
        }
        return null;
    }

    /**
     * 下划线命名法字段转驼峰命名法字段
     * @param o
     * @param targetClass
     * @param <T>
     * @return
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public static <T> T underScoreCase2CamelCase(Object o,Class<T> targetClass) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        T t = targetClass.newInstance();
        Class<?> oClass = o.getClass(); // 源对象
        Field[] declaredFields = oClass.getDeclaredFields();
        for (Field field : declaredFields){ // 获取源对象的所有字段
            Annotation[] declaredAnnotations = field.getDeclaredAnnotations();
            for (Annotation annotation:declaredAnnotations){
                if (annotation instanceof Transform){
                    System.out.println(field.getName() + "字段需要映射到" + ((Transform) annotation).value());
                    String transform2 = ((Transform) annotation).value().toString(); // 字段转化目标
                    String filedName = field.getName().toString(); // 字段的名称
                    Class<?> type = field.getType(); // 字段的类
                    String getMethod = "get" +
                            filedName.substring(0,1).toUpperCase() +
                            filedName.substring(1,filedName.length());
                    Method declaredMethod1 = oClass.getDeclaredMethod(getMethod, null);
                    Object oValue = declaredMethod1.invoke(null); // 获取字段的值
                    String setMethod = "set" +
                            transform2.substring(0,1).toUpperCase() +
                            transform2.substring(1,transform2.length());
                    System.out.println("调用：" + setMethod);
                    Method declaredMethod = t.getClass().getDeclaredMethod(setMethod, type);

                    declaredMethod.invoke(oValue); // 注入值
                }
            }
        }
        return t;
    }
}
